import axios from 'axios'
var baseURL = process.env.BASE_API// 后端api
import store from '../store'
import router from '@/router'
import { Message } from 'element-ui'
import { getToken, getRefreshToken, setToken } from '@/utils/auth'
import { handleErrorCode } from '@/utils/handleErrorCode'
import * as api from '@/api/login'

/* Params
 **options：axios参数
 **msg：提示语
 **flg：（boolean）定义header：Content-Type
 **customize: （boolean）true:自定义提示语 false：使用统一配置的提示语
*/
export function fetchToken(options, msg, flg, customize) {
	return new Promise((resolve, reject) => {
		const instance = axios.create({
			timeout: 20000,
			baseURL,
			isRetryRequest: false, // 用来处理刷新token后重新请求的自定义变量
			headers: flg ? { 'Content-Type': 'application/x-www-from-urlencoded;charset=utf-8' } : { 'Content-Type': 'application/json' }
		})
		instance.interceptors.request.use( config => {
	  // 请求拦截器
	  	if (store.getters.token) {
	  		config.headers['encrypt-token'] = getToken()
	  		config.headers['client_type'] = 'WEBBACK'
	  	}
			return config
			}, err => {
			  console.log('error 请求拦截 : ', err)
			  return Promise.reject(err);
		 })
		instance.interceptors.response.use( response => {
		// 响应拦截器
			let res = response.data
			if (res) {
				switch (res.code) {
					case '1004':   // token过期
						let config = response.config
						console.log('拦截成功,刷新token')
						if (!config.isRetryRequest) {
							api.getNewToken(getRefreshToken()).then(res => {
								if (+res.code === 0) {
						      let newToken = res.data.access_token
						      setToken(newToken)
						      config.isRetryRequest = true
						      config.headers['encrypt-token'] = getToken()
						      config.baseURL = ''  // url中已经包含baseURL的部分
						      return instance(config) //重新请求
              	}
					    }).catch((err) => {  // 刷新token失败则跳转到登录页重新登录
					    	Message({
									message: '认证失败，请重新登录',
									type: 'warning',
									duration: 4 * 1000
								})
					    	store.dispatch('FedLogOut') // 前端退出
					    	router.push({ path: '/login' })
					    })
						}
					break
					case '0':
					if (msg) {
					Message({
						message: msg,
						type: 'success',
						duration: 2 * 1000
					})
					}
					resolve(res)
					break
					case '-1':
					Message({
						message: '系统存在异常，请重试',//'数据加载失败，请重试',
						type: 'error',
						duration: 2 * 1000
					})
					reject(res)
					break
					default:
					if (!customize) {
						handleErrorCode(response).then(res => { // 错误码处理
							reject(res)
						})
					} else {
						reject(res)
					}
					break
				}
			}
			return response
		},  err=> {
			if (!isProduction) {  // 生产环境开关
				if (err.response) {
					Message({
						message: `[HTTP - ${err.response.status}] ${err.response.statusText} `,
						type: 'error',
						duration: 4 * 1000
					})
					reject(err)
				} else {
					Message({
						message: '请求超时，请重试',
						type: 'error',
						duration: 2 * 1000
					})
					reject(err)
				}
			} else {
				Message({
					message: '呀，网络正在开小差，请重试',
					type: 'error',
					duration: 2 * 1000
				})
				reject(err)
			}
			return Promise.reject(err)
		})
		instance(options)
	})
}

export function fetchRefreshToken(options, flg, msg) {  // 退出登录专用
	return new Promise((resolve, reject) => {
		const instance = axios.create({
			timeout: 20000,
			baseURL,
			headers: flg ? { 'Content-Type': 'application/x-www-from-urlencoded;charset=utf-8', 'encrypt-token': getToken(), 'refresh_token':  getRefreshToken() } : { 'Content-Type': 'application/json', 'encrypt-token': getToken(), 'refresh_token':  getRefreshToken() }
		})
		instance(options)
		.then(response => {
			let res = response.data
			if (res.state === 0 || res.state === 1) {
				if (+res.code === 0) {
					if (msg) {
					Message({
						message: msg,
						type: 'success',
						duration: 2 * 1000
					})
					}
				} else {
					handleErrorCode(response).then(res => { // 错误码处理
						reject(res)
					})
				}
			}
			resolve(res)
		})
		.catch(error => {
			console.log('err' + error)// for debug
			Message({
				message: '呀，网络正在开小差，请重试',
				type: 'error',
				duration: 2 * 1000
			})
			reject(error)
		})
	})
}

export function fetch(options, flg, Authorization, msg, customize) { // 认证获取token使用
	var Author = {}
	if (Authorization) {
		Author = { 'Authorization': 'basic d2ViX2JhY2s6YTVhZmNmYjA0YzIwNDFjM2E0YjgzM2ZkNzI2ZjVlZTE=' }  // base64认证信息：web_back（PC后台）
	}
	return new Promise((resolve, reject) => {
		const instance = axios.create({
			timeout: 20000,
			baseURL,
			headers: flg ? Object.assign({}, { 'Content-Type': 'application/x-www-form-urlencoded' }, Author) : { 'Content-Type': 'application/json' }
		})
		instance.interceptors.response.use( response => {
		// 响应拦截器
			let res = response.data
			if (res) {
				switch (res.code) {
					case '0':
					if (msg) {
					Message({
						message: msg,
						type: 'success',
						duration: 2 * 1000
					})
					}
					resolve(res)
					break
					case '-1':
					Message({
						message: '系统异常，请重试',//'数据加载失败，请重试',
						type: 'error',
						duration: 2 * 1000
					})
					reject(res)
					break
					default:
					if (!customize) {
						handleErrorCode(response).then(res => { // 错误码处理
							reject(res)
						})
					} else {
						reject(res)
					}
					break
				}
			}
			return response
		},  err=> {
			if (!isProduction) {  // 生产环境开关
				if (err.response) {
					Message({
						message: `[HTTP - ${err.response.status}] ${err.response.statusText} `,
						type: 'error',
						duration: 4 * 1000
					})
					reject(err)
				} else {
					Message({
						message: '请求超时，请重试',
						type: 'error',
						duration: 2 * 1000
					})
					reject(err)
				}
			} else {
				Message({
					message: '呀，网络正在开小差，请重试',
					type: 'error',
					duration: 2 * 1000
				})
				reject(err)
			}
			return Promise.reject(err)
		})
		instance(options)
	})
}

export function fetchForUpload(options, json) {    // 上传
	return new Promise((resolve, reject) => {
		const instance = axios.create({
			timeout: 20000,
			baseURL,
			headers: {
				'Content-Type': 'multipart/form-data', 'encrypt-token': getToken()
			}
		})
		instance(options)
			.then(response => {
				handleErrorCode(response).then(res => { // 错误码处理
					reject(res)
				})
				resolve(response.data)
			}).catch(error => {
				console.log('err' + error)// for debug
				Message({
					message: '呀，网络正在开小差，请尝试重新上传',
					type: 'error',
					duration: 2 * 1000
				})
				reject(error)
			})
	})
}

export function fetchExport(options, fileName) {    // excel导出
	return new Promise((resolve, reject) => {
		const instance = axios.create({
			timeout: 20000,
			baseURL,
			headers: { 'Content-Type': 'application/json' },
			responseType: 'arraybuffer'  // 'blob'
		})
		instance.interceptors.request.use( config => {
	  // 请求拦截器
	  	if (store.getters.token) {
	  		config.headers['encrypt-token'] = getToken()
	  	}
			 return config
			 }, err => {
			  console.log('error 请求拦截 : ', err)
			  return Promise.reject(err);
		 })
		instance.interceptors.response.use(res=> {
      let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName)
        } else {
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          window.URL.revokeObjectURL(link.href)
          document.body.removeChild(link)
        }
        return res
		})
		instance(options)
	})
}
